package com.yunwushanhe.handler.security;

import com.alibaba.fastjson.JSON;
import com.yunwushanhe.bean.ret.ResponseResult;
import com.yunwushanhe.enums.AppHttpCodeEnum;
import com.yunwushanhe.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author  抬头看看天
 * @Date    2023/8/10 11:40
 * 授权失败处理器，需要在SpringSecurity配置类中进行注册配置
 */
@Slf4j
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        log.error("经过了授权失败处理器处理：{}",e.getMessage());
        e.printStackTrace();
        ResponseResult<AppHttpCodeEnum> result = ResponseResult.error(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        WebUtils.renderString(httpServletResponse, JSON.toJSONString(result));
    }
}
